<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="700px" @ok="handleSubmit" destroyOnClose>
    <MyAlert type="warning" message="所有的敏感数据保存之后不会明文展示, 请自己妥善保管" />
    <BasicForm @register="registerForm">
      <template #paramsAtWay>
        <a-alert description="当前渠道参数需要在支付方式上进行配置" type="info">
          <template #action>
            <a type="link" @click="handleGoPayWay">去配置</a>
          </template>
        </a-alert>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { commonFromSchema, ConfigPageType } from "./payIfConfig.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdatePayConfig } from "./payIfConfig.api"
  import { useMessage } from "/@/hooks/web/useMessage"
  const { createMessage } = useMessage()
  import MyAlert from "/@/components/My/MyAlert.vue"

  // 声明Emits
  const emit = defineEmits(["success", "register", "go-pay-way"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const rowId = ref("")
  const payIfConfig = ref<any>()
  //表单配置
  const [registerForm, { setProps, resetFields, setFieldsValue, validate, resetSchema, appendSchemaByField }] = useForm({
    layout: "vertical",
    labelWidth: "100%",
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  //表单赋值
  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    console.log("data: ", data)

    let showFooter = data?.showFooter ?? true
    setDrawerProps({ confirmLoading: false, showFooter })
    isUpdate.value = !!data?.isUpdate
    payIfConfig.value = data.payIfConfig
    const config = payIfConfig.value
    const mchInfo = data.mchInfo
    
    let schemas: any = []

    // 设置公共表单参数
    schemas.push.apply(schemas, commonFromSchema)
    schemas.push({
      field: config.ifName + "-" + config.mchTypeName + "-divider",
      component: "Divider",
      label: config.ifName + " " + config.mchTypeName + "配置",
    })

    let ifParams = {}
    if (config.configPageType == ConfigPageType.JSON) {
      let configParams: any = []
      // 是商户模式 & 商户类型为普通商户
      if (config.isMchMode == "1" && config.mchParams) {
        // 普通商户
        configParams = JSON.parse(config.mchParams || "[]")
      } else {
        console.warn("尚未处理的参数")
      }

      if (config.normalParamsScope == "payWay" && mchInfo.type == "1") {
        configParams = null
        schemas.push({
          field: "paramsAtWay",
          component: "Input",
          slot: "paramsAtWay",
          label: "",
        })
      }

      if (configParams) {
        configParams.forEach((e) => {
          schemas.push({
            field: e.field,
            label: e.label,
            show: e.show === undefined || e.show ? true : false,
            required: e.required ? e.required : false,
            componentProps: e.component === "MyUpload" ? { ...e.componentProps } : e.componentProps,
            helpMessage: e.helpMessage,
            defaultValue: e.defaultValue,
            component: e.component,
          })
        })
      }

      await resetSchema(schemas)
      if (typeof config === "object") {
        if (!config.ifParams) {
          config.ifParams = "{}"
        }
        try {
          ifParams = JSON.parse(config.ifParams)
        } catch (e) {
          console.error(e)
        }
      }
    } else {
      await resetSchema(schemas)
    }
    console.log("form-value: ", { ...ifParams, ...config })
    setFieldsValue({ ...ifParams, ...config })
    setProps({ disabled: !showFooter })
  })
  const getTitle = computed(() => (!unref(isUpdate) ? "新增支付接口配置" : "编辑支付接口配置"))

  const handleGoPayWay = () => {
    closeDrawer()
    emit("go-pay-way", payIfConfig)
  }
  async function handleSubmit() {
    try {
      let values = await validate()
      console.log("------------", values)
      setDrawerProps({ confirmLoading: true })
      let submitValues: any = {}
      submitValues.status = values.status
      submitValues.remark = values.remark
      submitValues.id = payIfConfig.value.id

      for (const key in values) {
        if (key.includes("-divider") || ["status", "remark", "id"].indexOf(key) != -1) {
          delete values[key]
        }
      }
      submitValues.ifParams = JSON.stringify(values)
      console.log("submit: ", submitValues)

      await saveOrUpdatePayConfig(submitValues, unref(isUpdate))
      closeDrawer()
      emit("success", { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } })
      createMessage.success("配置成功")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }
</script>
